#getattr
Description: Retrieve the value of an attribute. See also hasattr, delattr, and setattr.
def getattr(obj, name: str):
'''
Retrieve the value of an attribute.
:param obj: An object
:param name: The name of the attribute
'''
Example:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p = Person("Alice", 30)
print(p.name)
print(getattr(p, 'name'))
getattr(obj, name)
is equivalent toobj.name
. If the attribute does not exist, it raises anAttributeError
. You can optionally provide a default value:getattr(obj, 'missing_attr', default_value)
.